package com.infocollect.project.api.ui;

import com.infocollect.common.utils.ServletUtils;
import com.infocollect.framework.security.LoginUser;
import com.infocollect.framework.security.service.TokenService;
import com.infocollect.project.api.entity.TappMenuEntity;
import com.infocollect.project.api.entity.TappUserEntity;
import com.infocollect.project.api.helper.CurrentHelp;
import com.infocollect.project.api.helper.MapHelper;
import com.infocollect.project.api.req.UserPowerMenuReq;
import com.infocollect.project.api.service.ITappActionRoleService;
import com.infocollect.project.api.service.ITappMenuService;
import com.infocollect.project.api.service.ITappUserService;
import com.infocollect.project.api.vo.CurrentUserInfoVO;
import com.infocollect.project.api.vo.UserButtonActionVO;
import com.infocollect.project.form.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (TappMenu)表控制层
 *
 * @author makejava
 * @since 2019-12-25 10:32:29queryCurrentMenu
 */
@Api(value = "tappMenu", tags = "菜单信息")
@RestController
@RequestMapping("tappMenu")
public class TappMenuController {
    @Autowired
    private TokenService tokenService;
    /**
     * 服务对象
     */
    @Resource
    private ITappMenuService tappMenuService;
    /**
     * 服务对象
     */
    @Resource
    private ITappUserService tappUserService;

    @Autowired
    private ITappActionRoleService actionService;
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation("获取菜单信息")
    @GetMapping("selectOne")
    public R<TappMenuEntity> selectOne(Long id) {
        return R.newOk(this.tappMenuService.queryById(id)) ;
    }

    /**
     *
     * @param menu
     * @return
     */
    @ApiOperation("保存菜单信息")
    @PostMapping("SaveMenu")
    @ResponseBody
    public R<Object> SaveMenu(@RequestBody Map<String,String> menu) throws IOException {
        if(menu.get("FMenuName")==null||menu.get("FMenuName").length()==0){
            return R.newError("菜单名称不能为空!");
        }
        if(menu.get("FParentID")==null){
            return R.newError("参数传入错误!");
        }
        if(menu.get("FOrderIndex")==null){
            return R.newError("菜单排序不能为空!");
        }
        if(menu.get("FTYPE")==null){
            return R.newError("菜单类型不能为空!");
        }
        try {
            TappMenuEntity dataMenu =menu.get("FID")==null?null: this.tappMenuService.queryById(Long.parseLong(menu.get("FID")) );
//            CurrentUserInfoVO currentUserInfo= CurrentHelp.Ins.GetUser();
            LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
            if (dataMenu == null) {
                dataMenu=new TappMenuEntity();
                dataMenu.setFcreateby(currentUserInfo.getUserName());
                dataMenu.setFlastupdateby(currentUserInfo.getUserName());
                dataMenu.setFcreationdate(new Date());
                dataMenu.setFlastupdatedate(new Date());
                MapHelper.setObjectValue(dataMenu,menu);
                dataMenu.setFmenucode(GetMenuCode(Long.parseLong(menu.get("FParentID"))));
                dataMenu.setFnum(0);
                dataMenu.setFsate("1");
                dataMenu = this.tappMenuService.insert(dataMenu);

            }else{
                dataMenu.setFlastupdateby(currentUserInfo.getUserName());
                dataMenu.setFlastupdatedate(new Date());
                MapHelper.setObjectValue(dataMenu,menu);
                dataMenu= this.tappMenuService.update(dataMenu);
            }
            return R.newOk(dataMenu);
        }catch (Exception ex){
            return R.newError("保存报错！具体错误信息为："+ex);
        }
    }
    String GetMenuCode(Long pid){
        TappMenuEntity ptappmenu= this.tappMenuService.queryById(pid);
        ptappmenu.setFnum(ptappmenu.getFnum() + 1);
        String code = "";
        for (int i = 0; i < 5 - ptappmenu.getFnum().toString().length(); i++)
        {
            code = code + "0";
        }
        this.tappMenuService.update(ptappmenu);
        return ptappmenu.getFmenucode() + code + ptappmenu.getFnum().toString();
    }


    /**
     *
     * @param
     * @return
     */
    @ApiOperation("获取所有菜单信息")
    @PostMapping("GetAllMenu")
    @ResponseBody
    public R<Object> GetAllMenu() throws IOException
    {
        List<TappMenuEntity> menulist=tappMenuService.queryAll(null);
        return  R.newOk(getChildResourceByPId(menulist,null,null));
    }

    /**
     * 递归组装菜单树
     * @param menulist
     * @param pId
     * @return
     */
    List<Map<String,Object>> getChildResourceByPId(List<TappMenuEntity> menulist, Long pId, List<UserButtonActionVO> userButtonActionVOList){
        List<Map<String,Object>> child = new ArrayList<>();
        Map<String,String> mapslots=new HashMap<>();
        mapslots.put("icon","icon");
        menulist.forEach(ee->{
         List<String>    userActionCodeList=new ArrayList<>();
         if(userButtonActionVOList!=null){
             userActionCodeList=  userButtonActionVOList.stream().filter(entity->entity.getMenuId().equals(ee.getFid())).map(UserButtonActionVO::getActionCode)
                    .collect(Collectors.toList());
         }
            if(ee.getFparentid()!=null&&ee.getFparentid().equals(pId)){
                Map<String,Object> childitem=new HashMap<>();
                childitem.put("fid",ee.getFid());
                childitem.put("title",ee.getFmenuname());
                childitem.put("name",ee.getFmenuname());
                childitem.put("index",ee.getForderindex());
                childitem.put("code",ee.getFmenuurl());
                childitem.put("typeid",ee.getFtype());
                childitem.put("hide",ee.getFhide());
                childitem.put("icon",ee.getFicon());
                childitem.put("icontype",ee.getFicontype());
                childitem.put("scopedSlots",mapslots);
                childitem.put("procbid",pId);
                childitem.put("buttonPower",userActionCodeList);
                childitem.put("IsOpFrom",ee.getFisopfrom());
                childitem.put("children",getChildResourceByPId(menulist,ee.getFid(),userButtonActionVOList));
                child.add(childitem);
            }
           else if(pId==null&&ee.getFparentid()==null){
                Map<String,Object> childitem=new HashMap<>();
                childitem.put("fid",ee.getFid());
                childitem.put("title",ee.getFmenuname());
                childitem.put("name",ee.getFmenuname());
                childitem.put("index",ee.getForderindex());
                childitem.put("code",ee.getFmenuurl());
                childitem.put("typeid",ee.getFtype());
                childitem.put("scopedSlots",mapslots);
                childitem.put("hide",ee.getFhide());
                childitem.put("icon",ee.getFicon());
                childitem.put("icontype",ee.getFicontype());
                childitem.put("procbid",pId);
                childitem.put("buttonPower",userActionCodeList);
                childitem.put("IsOpFrom",ee.getFisopfrom());
                childitem.put("children",getChildResourceByPId(menulist,ee.getFid(),userButtonActionVOList));
                child.add(childitem);


            }

        });
     return child;
    }
    /**
     *
     * @param
     * @return
     */
    @ApiOperation("获取当前用户拥有菜单权限")
    @PostMapping("queryCurrentMenu")
    @ResponseBody
    public  R<Map<String,Object>> queryCurrentMenu(@RequestBody Map<String,String> param)  throws Exception {
        String menuCode=param.get("MenuCode");
        CurrentUserInfoVO currentUserInfo= CurrentHelp.Ins.GetUser();
        UserPowerMenuReq userPowerMenu=new UserPowerMenuReq();
        userPowerMenu.setUserName(currentUserInfo.getUserName());
        userPowerMenu.setDeptCode(currentUserInfo.getDeptcode());
        userPowerMenu.setOrganCode(currentUserInfo.getOrgancode());
        userPowerMenu.setMenuCode(menuCode);
        List<TappMenuEntity> menulist= tappMenuService.QueryUserPowerMenu(userPowerMenu);
        if(menulist.size()==0){
            return R.newOk();
        }
        List<UserButtonActionVO> userButtonActionList=  actionService.getCurrentMenuAction();
        List<Map<String,Object>> list;
        if(menuCode==null||menuCode.length()==0) {
            TappMenuEntity tappMenu=  menulist.stream().filter(e->e.getFparentid()==null).findFirst().get();
            list=getChildResourceByPId(menulist, tappMenu.getFid(),userButtonActionList);
        }
        else{
            TappMenuEntity tappMenu=new TappMenuEntity();
            tappMenu.setFmenucode(menuCode);
            tappMenu= tappMenuService.queryAll(tappMenu).stream().findFirst().get();
            list=getChildResourceByPId(menulist, tappMenu.getFid(),userButtonActionList);
        }
       TappUserEntity tappUser= tappUserService.queryById(currentUserInfo.getUserId());

        Map<String,Object> resultMapdata=new HashMap<String,Object>();
        resultMapdata.put("menuData",list);
        resultMapdata.put("userName",currentUserInfo.getUserName());
        resultMapdata.put("realaName",currentUserInfo.getRealaname());
        resultMapdata.put("userid",currentUserInfo.getUserId());
        resultMapdata.put("deptcode",currentUserInfo.getDeptcode());
        resultMapdata.put("deptname",currentUserInfo.getDeptname());
        resultMapdata.put("deptid",currentUserInfo.getDeptid());
        resultMapdata.put("organcode",currentUserInfo.getOrgancode());
        resultMapdata.put("organid",currentUserInfo.getOrganid());
        resultMapdata.put("organname",currentUserInfo.getOrganname());
        if(tappUser.getFheadimg()!=null&&tappUser.getFheadimg().length()>0) {
            resultMapdata.put("HEADIMGURL", tappUser.getFheadimg());
        }
        else {
            resultMapdata.put("HEADIMGURL", "/DefaultAvatar.jpg");
        }
        return R.newOk(resultMapdata);

    }
    /**
     *
     * @param
     * @return
     */
    @ApiOperation("删除菜单信息")
    @PostMapping("delete")
    @ResponseBody
   public R<Object> delete(@RequestBody Map<String,String> param) throws Exception{
        String FID=param.get("FID");
        if(!StringUtils.isNotBlank(FID)){
            return R.newError("参数FID不能为空！");
        }
        tappMenuService.deleteById(Long.parseLong(FID));
        return R.newOk("删除成功！");
   }
}
